//Given a pattern and a string s, find if s follows the same pattern. 
//
// Here follow means a full match, such that there is a bijection between a lett
//er in pattern and a non-empty word in s. 
//
// 
// Example 1: 
//
// 
//Input: pattern = "abba", s = "dog cat cat dog"
//Output: true
// 
//
// Example 2: 
//
// 
//Input: pattern = "abba", s = "dog cat cat fish"
//Output: false
// 
//
// Example 3: 
//
// 
//Input: pattern = "aaaa", s = "dog cat cat dog"
//Output: false
// 
//
// Example 4: 
//
// 
//Input: pattern = "abba", s = "dog dog dog dog"
//Output: false
// 
//
// 
// Constraints: 
//
// 
// 1 <= pattern.length <= 300 
// pattern contains only lower-case English letters. 
// 1 <= s.length <= 3000 
// s contains only lower-case English letters and spaces ' '. 
// s does not contain any leading or trailing spaces. 
// All the words in s are separated by a single space. 
// 
// Related Topics 哈希表 字符串 
// 👍 388 👎 0


package leetcode.editor.cn;

import java.util.LinkedHashMap;

//Java：Word Pattern
class P290WordPattern {
    public static void main(String[] args) {
        Solution solution = new P290WordPattern().new Solution();
        // TO TEST
        solution.wordPattern("abc", "dog cat dog");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public boolean wordPattern(String pattern, String s) {
            String[] arr = s.split(" ");
            LinkedHashMap<Character, Integer> patternMap = new LinkedHashMap<>();
            LinkedHashMap<String, Integer> strMap = new LinkedHashMap<>();
            int len1 = pattern.length();
            int len2 = arr.length;
            if (len1 != len2) {
                return false;
            }
            for (int i = 0; i < len1; i++) {
                char c = pattern.charAt(i);
                String str = arr[i];
                if (patternMap.containsKey(c) || strMap.containsKey(str)) {
                    Integer index1 = patternMap.get(c);
                    Integer index2 = strMap.get(str);
                    if (index1 == null || index2 == null || !index1.equals(index2)) {
                        return false;
                    }
                } else {
                    patternMap.put(c, i);
                    strMap.put(str, i);
                }
            }
            return true;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}